package com.wzh.glsc.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wzh.common.constant.AuthServerConstant;
import com.wzh.common.constant.WeiBoAppConstant;
import com.wzh.common.utils.HttpUtils;
import com.wzh.common.utils.R;
import com.wzh.common.vo.MemberVo;
import com.wzh.glsc.auth.feign.MemberFeignService;
import com.wzh.glsc.auth.to.MemberTo;
import com.wzh.glsc.auth.vo.WeiBoAccessToken;
import lombok.extern.log4j.Log4j2;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xiaoming
 * @PackageName:com.wzh.glsc.auth.controller
 * @ClassName:@{NAME}
 * @Description:
 * @date:@{DATE}@{TIME}
 */
@Log4j2
@Controller
public class OAuth2Controller {

    @Resource
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2/weibo/success")
    public String weibo(@RequestParam String code, HttpSession session) throws Exception {
        Map<String,String> map=new HashMap<>();
        map.put("client_id", WeiBoAppConstant.WEIBO_APP_KEY);
        map.put("client_secret", WeiBoAppConstant.WEIBO_APP_SECRET);
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", WeiBoAppConstant.WEIBO_REDIRECT_URI);
        map.put("code", code);
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token",
                "post", new HashMap<>(), null, map);
        if(post.getStatusLine().getStatusCode()==200){
            //阿帕奇提供的实体类工具 这里把实体类转成json
            String json = EntityUtils.toString(post.getEntity());
            //再用阿里的jackjson转成实体类
            WeiBoAccessToken weiBoAccessToken = JSON.parseObject(json, WeiBoAccessToken.class);
            // 拿到了用户微博的信息
            // 用户如果是第一次登录就把信息存入数据库
            //如果不是第一次登录就把token存入数据库，并返回登录信息
            R r = memberFeignService.weiboLogin(weiBoAccessToken);
            if(r.getCode()==0){
                MemberTo memberTo = r.getData(new TypeReference<MemberTo>(){});
                MemberVo memberVo=new MemberVo();
                BeanUtils.copyProperties(memberTo,memberVo);
                session.setAttribute(AuthServerConstant.LOGIN_USEER, memberVo);
                log.info("登录成功:用户{}",memberVo.toString());
                return "redirect:http://gulimall.com";
            }else{
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
